<template>
  <div class="mt10 signBox">
    <div class="signBox__tools">
      <span v-if="inMobile">使用正楷在方框内签名！</span>
      <span v-else>按住鼠标左键，使用正楷在方框内签名！</span>
    </div>
    <div class="signBox__btns">
      <el-button type="text" @click="overwrite" icon="el-icon-refresh-left">重签</el-button>
      <el-button v-if="showConfirmBtn" type="text" @click="commit" icon="el-icon-refresh-left">提交</el-button>
    </div>
    <div class="canvasBox" ref="canvasHW" >
      <canvas
        ref="canvasF"
        id="canvasF"
        @touchstart="touchStart"
        @touchmove="touchMove"
        @touchend="touchEnd"
        @mousedown="mouseDown"
        @mousemove="mouseMove"
        @mouseup="mouseUp"
        @mouseleave="mouseLeave"
        :width="canvasWidth"
        :height="canvasHeight"
      ></canvas>
    </div>
    <div v-if="imgUrl">
      <img :src="imgUrl" alt="">
    </div>
  </div>
</template>
<script>
import { inMobile } from '@/utils/common'
export default {
  name: "SignTure",
  props : ["signImagePath"],
  data() {
    return {
      points: [],
      myCanvas: null,
      canvasTxt: null,
      lineWidth: 4,
      lineColor: "#222",
      startX: 0,
      startY: 0,
      canvasWidth: 500,
      canvasHeight: 220,
      isDown: false,
      stageInfo : null,
      imgUrl: null,
      inMobile: inMobile(),
      showConfirmBtn : false
    }
  },
  mounted(){
    this.init();
    console.log(this.signImagePath)
  },

  methods: {
    init(){
      this.canvasWidth = this.$refs['canvasHW'].clientWidth;
      //1.获取canvas
      this.myCanvas = this.$refs['canvasF'];
      //获取2d对象
      this.canvasTxt = this.$refs['canvasF'].getContext("2d");
      this.stageInfo = this.$refs['canvasF'].getBoundingClientRect();
    },
    //判断canvas是否绘制签名
    isCanvasBlank() {
      //PNG 算法
      let canvas = this.$refs['canvasF'];
      let blank = document.createElement('canvas');
      blank.width = canvas.width;
      blank.height = canvas.height;
      return canvas.toDataURL() === blank.toDataURL();
      //return !canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height).data.some(function(channel){return channel !==0;})
    },
    //mobile
    touchStart(ev) {
      ev = ev || event
      ev.preventDefault();
      let offset = this.myCanvas.getBoundingClientRect();
      if (ev.touches.length === 1) {
        let obj = {
          x: ev.targetTouches[0].clientX - offset.left,
          y: ev.targetTouches[0].clientY - offset.top
        }
        this.isDown = true;
        this.drawLine(obj.x, obj.y, false);
        this.points.push(obj)
      }
    },
    touchMove(ev) {
      ev = ev || event;
      ev.preventDefault();
      let offset = this.myCanvas.getBoundingClientRect();
      if (ev.touches.length === 1 && this.isDown) {
        let obj = {
          x: ev.targetTouches[0].clientX - offset.left,
          y: ev.targetTouches[0].clientY - offset.top
        }
        this.drawLine(obj.x, obj.y, true);
        this.points.push(obj)
      }
    },
    touchEnd(ev) {
      ev = ev || event
      ev.preventDefault()
      this.isDown = false
      if (ev.touches.length === 1) {
        let obj = {
          x: ev.targetTouches[0].clientX - this.stageInfo.left,
          y: ev.targetTouches[0].clientY - this.stageInfo.top
        }
        /*this.canvasTxt.beginPath()
        this.canvasTxt.moveTo(this.startX, this.startY)
        this.canvasTxt.lineTo(obj.x, obj.y)
        this.canvasTxt.stroke()
        this.canvasTxt.closePath()*/
        this.points.push(obj)
      }
    },
    //pc
    mouseDown(ev) {
      ev = ev || event
      ev.preventDefault()
      let obj = {
        x: ev.offsetX,
        y: ev.offsetY
      }
      this.drawLine(obj.x, obj.y, false);
      this.points.push(obj);
      this.isDown = true;
    },
    mouseMove(ev) {
      ev = ev || event
      ev.preventDefault()
      if (this.isDown) {
        let obj = {
          x: ev.offsetX,
          y: ev.offsetY
        }
        this.drawLine(obj.x, obj.y, true);
        this.points.push(obj)
      }
    },
    mouseUp(ev) {
      ev = ev || event;
      ev.preventDefault();
      this.isDown = false
      this.points.push({ x: -1, y: -1 });
    },
    mouseLeave(ev) {
      //this.isDown = false
    },
    //画线
    drawLine(x, y, isDraw) {
      if (isDraw) {
        this.canvasTxt.beginPath();
        this.canvasTxt.lineWidth = this.lineWidth; //设置线宽状态
        this.canvasTxt.strokeStyle = this.lineColor; //设置线的颜色状态
        this.canvasTxt.lineCap = 'round'
        this.canvasTxt.lineJoin = "round";
        this.canvasTxt.moveTo(this.startX, this.startY);
        this.canvasTxt.lineTo(x, y);
        this.canvasTxt.stroke();
        this.canvasTxt.closePath();
      }
      // 每次移动都要更新坐标位置
      this.startX = x;
      this.startY = y;
    },
    //重写
    overwrite() {
      this.canvasTxt.clearRect(0, 0, this.$refs.canvasF.width, this.$refs.canvasF.height)
      this.points = [];
      this.imgUrl = null;
    },
    //提交签名
    dataURLtoFile(dataurl, filename) { // 将base64转换为file文件
      let arr = dataurl.split(',')
      let mime = arr[0].match(/:(.*?);/)[1]
      let bstr = atob(arr[1])
      let n = bstr.length
      let u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename, { type: mime })
    },
    getBase64Img(){
      if(this.isCanvasBlank()){
        this.$message({
          message: "请正确签名！",
          type: "warning"
        });
        return false
      }
      return this.$refs.canvasF.toDataURL('image/png')
    },
    getFiles(){
      let base64Img = this.$refs.canvasF.toDataURL();
      let picName = 'sign.png';
      let files = this.dataURLtoFile(base64Img, picName);
      return files
    },

    commit() {
      if(this.isCanvasBlank()){
        this.$message({
          message: "请正确签名！",
          type: "warning"
        });
        return
      }
      console.log(this.isCanvasBlank());
      this.imgUrl = this.$refs.canvasF.toDataURL();
      let base64Img = this.$refs.canvasF.toDataURL();
      let picName = 'pic.png';
      let files = this.dataURLtoFile(base64Img, picName);
      let formData = new FormData();
      formData.append('file', files);
    }
  }
}
</script>
<style lang="scss" scoped>
  .signBox {
    position: relative;
  }
  .signBox__btns {
    position: absolute;
    right: 10px;
    top: 0;
  }
  .signBox__tools {
    position: absolute;
    top: 10px;
    left: 10px;
    font-size: 12px;
    color: gray;
  }
  .canvasBox {
    border-radius: 10px;
    border: 3px dashed #ddd;
    canvas {
      margin: 0 auto;
    };
    background-repeat:no-repeat;
	background-size:100% 100%;
	-moz-background-size:100% 100%;
  }
</style>
